package com.h3bpm.web.portal.controller;

import OThinker.Common.Organization.Models.Unit;
import OThinker.Common.Organization.Models.User;
import OThinker.Common.Organization.enums.State;
import OThinker.Common.Organization.enums.UnitType;
import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Entity.DataModel.BizObject;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import com.alibaba.fastjson.JSONObject;
import com.h3bpm.base.util.AppUtility;
import com.h3bpm.web.common.domin.EsbReqHead;
import com.h3bpm.web.common.utils.HttpLocalUtils;
import com.h3bpm.web.common.utils.SqlUtil;
import com.h3bpm.web.msg.util.JSONUtils;
import com.h3bpm.web.util.DateUtil;
import data.DataRow;
import data.DataTable;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 通知公告推送
 */
@RestController
@RequestMapping("/Portal/announcement")
public class AnnouncementController extends ControllerBase {

    @Value("${esb.url}")
    public String ESBURL;
    @Value("${esb.sourceSystem}")
    public String sourceSystem;
    @Value("${esb.targetSystem}")
    public String targetSystem;
    @Value("${esb.noticeServiceName}")
    public String noticeServiceName;

    private final static Logger logger = LoggerFactory.getLogger(AnnouncementController.class);

    @Override
    public String getFunctionCode() {
        return null;
    }

    /**
     * 推送通知公告
     * @return
     */
    @RequestMapping("/addAnnouncement")
    @ResponseBody
    public void getReportNos(String instanceId){
        try {
            InstanceData instanceData = new InstanceData(AppUtility.getEngine(), instanceId, User.AdministratorID);
            BizObject bizObject = instanceData.getBizObject();
            String publisher = (String)bizObject.GetValue("publisher");
            String publishTime = DateUtil.format((Date)bizObject.GetValue("publishTime"));
            String title = (String)bizObject.GetValue("title");
            String publisherDept = (String)bizObject.GetValue("publisherDept");
            String docNum = (String)bizObject.GetValue("refNo");
            String draftDept = (String)bizObject.GetValue("dept");
//            Object content = bizObject.GetValue("content");
            String visibleRange = "";
            String publishScopeStr = (String)bizObject.GetValue("publishScopeStr");

            if(StringUtils.isNotBlank(publishScopeStr)&&publishScopeStr.equals("*")){
                visibleRange = publishScopeStr;
            }else{
                List<Unit> units = instanceData.getEngine().getOrganization().GetUnits(Arrays.asList(publishScopeStr.split(",")));
                visibleRange = getCode(units);
            }
            List<Map<String, Object>> attachment = getAttachmentByObjectId(bizObject.getObjectID(),"attachment");
            String type = (String)bizObject.GetValue("type");
            Map map = new HashMap();
            map.put("noticeTitle",title);
            map.put("noticeType",type);
            map.put("createTime",publishTime);
            map.put("createBy",publisher);
            map.put("createOrg",publisherDept);
            map.put("fileInfo",attachment);
            map.put("docNum",docNum);
            map.put("draftDept",draftDept);
//            map.put("noticeContent",content);
            map.put("visibleRange", visibleRange);
            String json= JSONUtils.toJson(map);
            logger.info("推送通知公告至portal参数,json:"+json);
            //通知公告推送portal
            String result = HttpLocalUtils.doPostToESB(ESBURL, json ,new EsbReqHead(
                    sourceSystem, targetSystem, UUID.randomUUID().toString(), noticeServiceName));
            logger.info("推送通知公告至portal结果,result:"+result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 本部门OD
     * @param originatorOU
     */
    @RequestMapping("/getOUUser")
    @ResponseBody
    public JSONObject getOUUser(String originatorOU){
        List<String> Units = new ArrayList<>();
        try {
            Units = this.getEngine().getOrganization().GetChildren(originatorOU, UnitType.User, false, State.Active);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject result = new JSONObject();
        result.put("state", "200");
        result.put("msg", "success");
        result.put("data", StringUtils.join(Units, ","));
        return result;
    }

    private String getCode(List<Unit> units){
        String codes = "";
        for (int i = 0; i < units.size(); i++) {
            String code = ((User)units.get(i)).getCode();
            //附件名称、附件上传路径
            if(i == units.size()-1){
                codes += code;
            }else{
                codes += code+",";
            }
        }
        return codes;
    }

    /**
     * 获取附件信息：多个附件通过分号拼接，名称和地址用逗号拼接
     *
     * @param objectId
     * @return
     * @throws Exception
     */
    private List<Map<String, Object>> getAttachmentByObjectId(String objectId, String dataField) throws Exception {
        String sql = "SELECT dataField,fileName,contentType,contentLength,storagePath,DownloadUrl,CreatedTime FROM ot_attachment WHERE " +
                "BizObjectId='"+objectId+"' and dataField='"+dataField+"'";
        List<Map<String, Object>> list = new ArrayList<>();
        DataTable data = SqlUtil.doQuery(sql);
        List<DataRow> attList = data.getEntityRows();
        for (int i = 0; i < attList.size(); i++) {
            Map<String,Object> map = new HashMap<>();
            map.put("filePath",attList.get(i).getString("DownloadUrl"));
            map.put("fileSize",attList.get(i).getString("contentLength"));
            map.put("createTime",attList.get(i).getString("CreatedTime"));
            map.put("fileName",attList.get(i).getString("fileName"));
            list.add(map);
        }
        return list;
    }

}
